package com.shuyihui.databindinglib;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 使用 ViewBinding 并使用ViewModel
 * @param <VDB>
 * @param <VM> 继承BaseViewModel
 */
public abstract class BaseMFragment<VDB extends ViewBinding,VM extends BaseViewModel> extends BaseDFragment<VDB> {
    protected VM mViewModel;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        createViewModel();
    }

    /**
     * 没有用到则要重写
     */
    protected void createViewModel() {
        if (mViewModel == null) {
            Class modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1];
                mViewModel = (VM) new ViewModelProvider(this).get(modelClass);
            }
        }
    }
}
